# == Schema Information
# Schema version: 38
#
# Table name: schools
#
#  id                  :integer(11)     not null, primary key
#  area_id             :integer(11)
#  submitor_id         :integer(11)
#  info_source         :string(255)
#  is_validate         :boolean(1)
#  is_hidden           :boolean(1)
#  created_at          :datetime
#  updated_at          :datetime
#  title               :string(255)
#  address             :string(255)
#  zipcode             :integer(11)
#  master              :string(255)
#  telephone           :string(255)
#  contact_name        :string(255)
#  contact_role        :string(255)
#  contact_telephone   :string(255)
#  contact_email       :string(255)
#  level_amount        :string(255)
#  teacher_amount      :string(255)
#  class_amount        :string(255)
#  student_amount      :string(255)
#  has_library         :integer(1)
#  has_pc              :integer(1)
#  has_internet        :integer(1)
#  book_amount         :integer(11)
#  pc_amount           :integer(11)
#  incoming_from       :string(255)
#  incoming_average    :integer(1)
#  has_ngo             :integer(1)
#  ngo_name            :string(255)
#  ngo_start_at        :date
#  ngo_contact_name    :string(255)
#  ngo_contact_via     :string(255)
#  traffic_sights      :string(255)
#  traffic_type        :string(255)
#  traffic_duration    :string(255)
#  traffic_description :text
#  traffic_charge      :string(255)
#  books_need          :string(255)
#  stationaries_need   :string(255)
#  sports_need         :string(255)
#  clothes_need        :string(255)
#  accessories_need    :string(255)
#  others_need         :string(255)
#  classes_need        :string(255)
#  teachers_need       :string(255)
#  finder_name         :string(255)
#  finder_qq           :string(255)
#  finder_msn          :string(255)
#  finder_email        :string(255)
#  finder_survey_at    :date
#  advice              :text
#  advice_html         :text
#  is_meta             :boolean(1)
#  edu_type            :integer(11)
#  urgency_need        :string(255)
#

class School < ActiveRecord::Base
  # edu_type
  # 1 小学
  # 2 中学
  # 3 临时安置点，帐篷学校
  # 4 板房学校
  
  acts_as_taggable
  
  belongs_to :submitor, :class_name => 'User', :foreign_key => 'submitor_id'
  belongs_to :area
  has_many :photos
  has_many :students
  has_many :visiteds, :dependent => :destroy
  has_many :travelers, :class_name => "User", :through => :visiteds, :foreign_key => "user_id", :source => :traveler, :dependent => :destroy
  has_many :comments, :class_name => 'SchoolComment', :dependent => :destroy
  
  validates_presence_of :title, :address, :area_id
  validates_uniqueness_of :title, :case_sensitive => false
  
  format_attribute :advice
  
  def after_create
    Mailer.deliver_submitted_school_notification(self)
  end
  
  def editable_by?(user)
    unless is_validate?
      return user!=:false && (submitor_id == user.id || user.is_school_admin?)
    else
      return user!=:false && user.is_school_admin?
    end
  end
  
  def visited_by(user)
    visited = Visited.find(:first, :conditions => {:school_id => id, :user_id => user.id})
    if visited.nil?
      return :false
    else
      return visited.visit_at.to_s
    end
  end 
  
  def build_tags
    tags_arr = (urgency_need + books_need + stationaries_need + sports_need + clothes_need + accessories_need + classes_need + teachers_need + others_need).split(" ").to_a
    tags_arr.collect {|t| t.gsub!(" ", "")}
    tags_arr
  end
  
  def self.submitted_by(user, is_validate=true)
    find(:all, :conditions => {:is_hidden => false,
                               :is_validate => is_validate,
                               :submitor_id => user.id}, :order => "schools.updated_at desc",
               :select => "id, title, updated_at")
  end
  
  def self.valid
    self.find(:all, 
              :conditions => {:is_validate => true, :is_hidden => false}, 
              :order      => "schools.updated_at desc", 
              :limit      => 15, 
              :include    => :submitor)
  end
  
  def self.past_month(n=1)
    past_month = Date.today << n # n 个月之前
    self.find(:all, :conditions => 
              ["is_validate = ? and is_hidden = ? and created_at > ?", true, false, past_month])
    # self.find(:all, :conditions => ["is_validate = ? and is_hidden = ? and created_at between '2008-04-01' and '2008-05-01'", true, false])
    #self.find_by_sql("select id,title,created_at from schools where created_at between '2008-04-01' and '2008-05-01'")
  end
  
  def self.show_date(year, month, day, valid)
    self.find(:all, 
              :order      => "schools.updated_at desc",
              :conditions => ["created_at LIKE ? and is_validate = ? and is_hidden = ? ", "#{year}-#{month}-#{day}%", valid, false])
  end
  
  def self.archives(valid = true)
    date_func = "extract(year from created_at) as year,extract(month from created_at) as month"
    
    counts = School.find_by_sql(["select count(*) as count, #{date_func} from schools where is_validate = ? and is_hidden = ? and created_at < ? group by year,month order by year asc,month asc limit ? ", valid, false, Time.now,count.to_i])
    
    sum = 0
    result = counts.map do |entry|
      sum += entry.count.to_i
      {
        :name => entry.year + "年" + entry.month + "月",
        :month => entry.month.to_i,
        :year => entry.year.to_i,
        :delta => entry.count,
        :sum => sum
      }
    end
    return result.reverse
  end
  
end
